package com.letoken.platform.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.app.service.AppUserIssueService;
import com.letoken.platform.app.service.AppUserWalletService;
import com.letoken.platform.app.service.QuickSwapService;
import com.letoken.platform.pub.enums.*;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.util.BigDecimalUtil;
import com.letoken.platform.pub.util.UUIDUtil;
import com.letoken.platform.repo.admin.dao.AdminCardConfigMapper;
import com.letoken.platform.repo.admin.dao.AdminSwapConfigMapper;
import com.letoken.platform.repo.admin.po.AdminSwapConfig;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.admin.manager.AdminIssueConfigManager;
import com.letoken.platform.repo.admin.manager.AdminSwapConfigManager;
import com.letoken.platform.repo.admin.po.AdminIssueConfig;
import com.letoken.platform.repo.admin.po.AppUserSwapRecord;
import com.letoken.platform.repo.app.manager.AppUserLockedManager;
import com.letoken.platform.repo.app.manager.AppUserManager;
import com.letoken.platform.repo.app.manager.AppUserWalletManager;
import com.letoken.platform.repo.app.po.*;
import com.letoken.platform.repo.app.redis.AppWalletBlackListRedis;
import com.letoken.platform.repo.app.redis.AppWalletRateLimitRedis;
import com.letoken.platform.repo.app.req.user.AppUserMintLetReq;
import com.letoken.platform.repo.app.req.user.AppUserSwapReq;
import com.letoken.platform.repo.mall.dao.AppIssueCardInfoMapper;
import com.letoken.platform.repo.performance.TeamPerformanceService;
import com.letoken.platform.repo.utlis.UserLockedTool;
import com.letoken.platform.repo.utlis.WebUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author wyl
 * @date 2022/12/20 16:49
 * @Version 1.0
 */
@Service
@Log4j2
public class QuickSwapServiceImpl implements QuickSwapService {

    @Autowired
    private AppUserWalletManager walletManager;

    @Resource
    private AppUserWalletMapper walletMapper;

    @Autowired
    private AdminSwapConfigManager adminSwapConfigManager;

    @Autowired
    private AdminSwapConfigMapper adminSwapConfigMapper;

    @Autowired
    private AdminIssueConfigManager adminIssueConfigManager;

    @Autowired
    private AppUserWalletService wallService;

    @Autowired
    private AppUserIssueService appUserIssueService;

    @Resource
    private AppUserIssueMapper appUserIssueMapper;

    @Resource
    private TokenMapper tokenMapper;

    @Autowired
    private AppUserTeamMapper appuserTeamMapper;

    @Autowired
    private AppUserManager appUserManager;

    @Resource
    private AppUserLockedManager appUserLockedManager;

    @Resource
    private AppIssueCardInfoMapper appIssueCardInfoMapper;


    @Resource
    private AdminCardConfigMapper adminCardConfigMapper;


    @Resource
    AppUserWalletMapper appUserWalletMapper;

    @Resource
    AppUserExchangeInfoMapper appUserExchangeInfoMapper;

    @Resource
    private TeamPerformanceService teamPerformanceService;

    /**
     * 用户闪兑
     *
     * @param req
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void exchange(AppUserSwapReq req) {
        Integer userId = WebUtils.getUserId();
        // 判断冻结用户
        if(appUserLockedManager.isLocked(userId)){
            throw new ApiServiceException("闪兑失败!");
        }
        QueryWrapper<AdminSwapConfig> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("token_id",req.getFromType());
        queryWrapper.eq("to_token_id",req.getToType());
        queryWrapper.eq("switchs",1);
        AdminSwapConfig adminSwapConfig = adminSwapConfigMapper.selectOne(queryWrapper);
        if(Objects.isNull(adminSwapConfig)){
            throw new ApiServiceException("闪兑配置不存在!");
        }
        BigDecimal toAmount = req.getFromAmount().divide(adminSwapConfig.getPrice(),10, RoundingMode.HALF_UP);

//        if(adminSwapConfig.getIsQuota().equals(1)){
//            QueryWrapper<AppUserExchangeInfo> query = new QueryWrapper<>();
//            query.eq("user_id",userId);
//            AppUserExchangeInfo appUserExchangeInfo = appUserExchangeInfoMapper.selectOne(query);
//            if (Objects.isNull(appUserExchangeInfo)) {
//                throw new ApiServiceException("闪兑额度0!");
//            }else if(toAmount.compareTo(appUserExchangeInfo.getAmount().multiply(new BigDecimal(adminSwapConfig.getQuota())))>0){
//                throw new ApiServiceException("闪兑额度小于可兑换额度!");
//            }
//            appUserExchangeInfo.setAmount(appUserExchangeInfo.getAmount().subtract(toAmount.divide(new BigDecimal(adminSwapConfig.getQuota()),10, RoundingMode.HALF_UP)));
//            appUserExchangeInfo.updateById();
//        }

        //减少兑换源金额
        Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(req.getFromType(),userId);
        if ( ObjectUtils.isEmpty(walletId)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_051);
        }

        AppUserWallet w = appUserWalletMapper.selectForUpdate(walletId);
        if (w.getAvailableBalance().compareTo(req.getFromAmount()) < 0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_053);
        }
        if (req.getFromAmount().compareTo(new BigDecimal(adminSwapConfig.getMinSwapCount()))<0 || req.getFromAmount().compareTo(new BigDecimal(adminSwapConfig.getMaxSwapCount()))>0){
            throw new ApiServiceException("兑换数量区间在"+adminSwapConfig.getMinSwapCount()+"~"+adminSwapConfig.getMaxSwapCount());
        }
        AppUserWallet updateW = new AppUserWallet();
        updateW.setId(walletId);
        updateW.setAvailableBalance(w.getAvailableBalance().subtract(req.getFromAmount()));
        appUserWalletMapper.updateById(updateW);
        //增加兑换后币种金额
        Integer walletId2 = appUserWalletMapper.checkoutTokenIdAndUserId(req.getToType(),userId);
        if ( ObjectUtils.isEmpty(walletId)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_051);
        }
        AppUserWallet w2 = appUserWalletMapper.selectForUpdate(walletId2);
        AppUserWallet updateW2 = new AppUserWallet();
        updateW2.setId(walletId2);

        updateW2.setAvailableBalance(w2.getAvailableBalance().add(toAmount));
        appUserWalletMapper.updateById(updateW2);


        String uuid = UUIDUtil.getUUID(16);
        AppUserSwapRecord record = new AppUserSwapRecord();
        record.setUserId(userId);
        record.setOrderId(uuid);
        record.setFromType(req.getFromType());
        record.setFromTypeName(LetokenTokenTypeEnum.getName(req.getFromType()));
        record.setFromAmount(req.getFromAmount());
        record.setToType(req.getToType());
        record.setToTypeName(LetokenTokenTypeEnum.getName(req.getToType()));
        record.setToAmount(toAmount);
        record.setCreateTime(LocalDateTime.now());
        record.insert();

        AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
        assetHistory.setUserId(userId);
        assetHistory.setType(TokenTransactionTypeEnum.EXCHANGE.getValue());
        assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
        assetHistory.setTokenId(req.getFromType());
        assetHistory.setAmount(req.getFromAmount().negate());
        assetHistory.setSn(uuid);
        assetHistory.setBalance(updateW.getAvailableBalance());
        assetHistory.setCreateTime(LocalDateTime.now());
        assetHistory.setUpdateTime(assetHistory.getCreateTime());
        assetHistory.insert();


        AppUserAssetsHistory assetHistory2 = new AppUserAssetsHistory();
        assetHistory2.setUserId(userId);
        assetHistory2.setType(TokenTransactionTypeEnum.EXCHANGE.getValue());
        assetHistory2.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
        assetHistory2.setTokenId(req.getToType());
        assetHistory2.setAmount(toAmount);
        assetHistory2.setSn(uuid);
        assetHistory2.setBalance(updateW2.getAvailableBalance());
        assetHistory2.setCreateTime(LocalDateTime.now());
        assetHistory2.setUpdateTime(assetHistory.getCreateTime());
        assetHistory2.insert();

    }
    /*@Transactional(rollbackFor = Exception.class)
    @Override
    public void exchange(AppUserSwapReq req) {
        log.info("LetokenUserServiceImpl exchange req{},", JSONObject.toJSONString(req));
        Integer fromType = req.getFromType();
        BigDecimal fromAmount = req.getFromAmount();
        if (fromAmount.scale() > LetokenTokenConstant.AMOUNT_SCALE){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_WALLET_WITHDRAW_020);
        }
        //from闪兑配置
        AdminSwapConfig fromSwapConfig = adminSwapConfigManager.querySwapPrice(fromType);
        if (fromAmount.compareTo(new BigDecimal(fromSwapConfig.getMinSwapCount())) < 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_010);
        }

        if (fromAmount.compareTo(new BigDecimal(fromSwapConfig.getMaxSwapCount())) > 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_014);
        }
        Integer userId = WebUtils.getUserId();

        // 黑名单
        if(AppWalletBlackListRedis.me().getValue(userId.toString())){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_013);
        }

        // 频率限制
        if(AppWalletRateLimitRedis.me().isLimited(userId.toString(),"swap", 1)) {
            // 加入黑名单
            AppWalletBlackListRedis.me().setValue(userId.toString(), true);
            // 冻结用户
            appUserLockedManager.setUserLocked(userId, true);
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_013);
        }

        // 判断冻结用户
        if(appUserLockedManager.isLocked(userId)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_013);
        }

        Integer toType;
        Integer swapType;
        LambdaQueryWrapper<AppUserWallet> walletQueryWrapper = Wrappers.lambdaQuery();
        walletQueryWrapper.eq(AppUserWallet::getUserId, userId);
        if (fromType.equals(LetokenTokenTypeEnum.USDT.getId())) {
            walletQueryWrapper.in(AppUserWallet::getTokenId, fromType, LetokenTokenTypeEnum.LET.getId());
            toType = LetokenTokenTypeEnum.LET.getId();
            swapType = TokenTransactionTypeEnum.USDT_LET.getValue();
        } else if (fromType.equals(LetokenTokenTypeEnum.LET.getId())) {
            walletQueryWrapper.in(AppUserWallet::getTokenId, fromType, LetokenTokenTypeEnum.USDT.getId());
            toType = LetokenTokenTypeEnum.USDT.getId();
            swapType = TokenTransactionTypeEnum.LET_USDT.getValue();
        } else {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_001);
        }
        String proportion = this.doSwapProportion(fromType, toType);
        String[] split = proportion.split(":");
        BigDecimal fromPrice = new BigDecimal(split[0]);
        BigDecimal toPrice = new BigDecimal(split[1]);
        BigDecimal divide = BigDecimalUtil.divide(fromPrice,toPrice);
        //计算百分比
        BigDecimal toAmount = BigDecimalUtil.divide(fromAmount, divide).setScale(BigDecimal.ROUND_HALF_EVEN, RoundingMode.DOWN);
        List<AppUserWallet> appUserWalletList = walletMapper.selectList(walletQueryWrapper);
        if (CollUtil.isEmpty(appUserWalletList)) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_009);
        }
        AppUserWallet letWallet = null;
        AppUserWallet usdtWallet = null;
        AppUserWallet fromWallet = null;
        AppUserWallet toWallet = null;
        for (AppUserWallet wallet : appUserWalletList) {
            if (wallet.getTokenId().equals(LetokenTokenTypeEnum.USDT.getId())) {
                usdtWallet = wallet;
                if (fromType.equals(wallet.getTokenId())) {
                    fromWallet = wallet;
                } else {
                    toWallet = wallet;
                }
            } else if (wallet.getTokenId().equals(LetokenTokenTypeEnum.LET.getId())) {
                letWallet = wallet;
                if (fromType.equals(wallet.getTokenId())) {
                    fromWallet = wallet;
                } else {
                    toWallet = wallet;
                }
            }
        }
        //当前用户的闪兑金额是否大于用户对应代币的可用余额
        assert fromWallet != null;
        assert toWallet != null;
        assert usdtWallet != null;
        assert letWallet != null;
        if (fromAmount.compareTo(fromWallet.getAvailableBalance()) > 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_009);
        }
        letWallet.setUpdateTime(LocalDateTime.now());
        usdtWallet.setUpdateTime(letWallet.getUpdateTime());
        int fromFlag = wallService.updateUserAmountByUserIDandCoin(fromAmount.negate(),
                BigDecimal.ZERO, BigDecimal.ZERO, userId, fromType);

        if (fromFlag <= 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_013);
        }

        int toFlag = wallService.updateUserAmountByUserIDandCoin(toAmount,
                BigDecimal.ZERO, BigDecimal.ZERO, userId, toType);

        if (toFlag <= 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_013);
        }
        List<QueryTokenListRes> queryTokenListRes = tokenMapper.queryReTokenList();
        String fromTypeName = null;
        String toTypeName = null;
        for (QueryTokenListRes queryTokenListRe : queryTokenListRes) {
            if (queryTokenListRe.getId().equals(fromType)) {
                fromTypeName = queryTokenListRe.getName();
            }
            if (queryTokenListRe.getId().equals(toType)) {
                toTypeName = queryTokenListRe.getName();
            }
        }
        String uuid = UUIDUtil.getUUID(16);
        AppUserSwapRecord record = new AppUserSwapRecord();
        record.setUserId(userId);
        record.setOrderId(uuid);
        record.setFromType(fromType);
        record.setFromTypeName(fromTypeName);
        record.setFromAmount(fromAmount);
        record.setToType(toType);
        record.setToTypeName(toTypeName);
        record.setToAmount(toAmount);
        record.setCreateTime(LocalDateTime.now());
        boolean recordInsert = record.insert();
        if (!recordInsert) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_013);
        }

        AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
        assetHistory.setUserId(userId);
        assetHistory.setType(swapType);
        assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
        assetHistory.setTokenId(LetokenTokenTypeEnum.USDT.getId());
        if (swapType.equals(TokenTransactionTypeEnum.USDT_LET.getValue())){
            assetHistory.setAmount(fromAmount.negate());
        }else {
            assetHistory.setAmount(toAmount);
        }
        assetHistory.setSn(uuid);
        assetHistory.setCreateTime(LocalDateTime.now());
        assetHistory.setUpdateTime(LocalDateTime.now());
        assetHistory.insert();

        try {
            AppUserAssetsHistory updateAssetHistory = new AppUserAssetsHistory();
            updateAssetHistory.setBalance(walletMapper.getAvailableBalance(assetHistory.getTokenId(), assetHistory.getUserId()));
            updateAssetHistory.setId(assetHistory.getId());
            assetHistory.updateById();
        }catch (Exception e){
            log.error("更新余额失败 id{} eMsg{}", assetHistory.getId(), e.getMessage());
        }

        assetHistory.setId(null);
        assetHistory.setTokenId(LetokenTokenTypeEnum.LET.getId());
        assetHistory.setCreateTime(LocalDateTime.now());
        assetHistory.setUpdateTime(LocalDateTime.now());
        if (swapType.equals(TokenTransactionTypeEnum.USDT_LET.getValue())){
            assetHistory.setAmount(toAmount);
        }else {
            assetHistory.setAmount(fromAmount.negate());
        }
        assetHistory.insert();
        try {
            AppUserAssetsHistory updateAssetHistory = new AppUserAssetsHistory();
            updateAssetHistory.setBalance(walletMapper.getAvailableBalance(assetHistory.getTokenId(), assetHistory.getUserId()));
            updateAssetHistory.setId(assetHistory.getId());
            assetHistory.updateById();
        }catch (Exception e){
            log.error("更新余额失败 id{} eMsg{}", assetHistory.getId(), e.getMessage());
        }


    }*/


    /**
     * mint
     * 铸币发行
     *
     * @param req
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void MintLet(AppUserMintLetReq req) {
        log.info("LetokenUserServiceImpl MintLet req{},", JSONObject.toJSONString(req));
        BigDecimal mintAmount = req.getMintAmount();
        if (mintAmount.scale() != 0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_006);
        }
        AppUser user = appUserManager.queryMe();
        Integer userId = user.getId();

        // 黑名单
        if(AppWalletBlackListRedis.me().getValue(userId.toString())){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }

        // 频率限制
        if(AppWalletRateLimitRedis.me().isLimited(userId.toString(),"mint", 1)) {
            // 加入黑名单
            AppWalletBlackListRedis.me().setValue(userId.toString(), true);
            // 冻结用户
            UserLockedTool.submit(()->{
                appUserLockedManager.setUserLocked(userId, true);
            });
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }

        // 判断冻结用户
        if(appUserLockedManager.isLocked(userId)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }

        AdminIssueConfig mintConfig = adminIssueConfigManager.queryLet();
        if (mintAmount.compareTo(new BigDecimal(mintConfig.getMinIssueCount())) < 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_003);
        }
        if (mintAmount.compareTo(new BigDecimal(mintConfig.getMaxIssueCount())) > 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_004);
        }
        //查询发行奖励
        BigDecimal rewardCount;
        if(mintAmount.compareTo(mintConfig.getIssueAmount())>=0){
            rewardCount =  BigDecimalUtil.multiply(mintAmount, new BigDecimal(mintConfig.getRate())).divide(new BigDecimal(100));
           // Integer count = mintAmount.divideToIntegralValue(mintConfig.getIssueAmount()).intValue();
            /*AdminCardConfig adminCardConfig = adminCardConfigMapper.selectById(1);
            BigDecimal acceleration = BigDecimalUtil.multiply(mintAmount, new BigDecimal(mintConfig.getCirculateRate())).divide(new BigDecimal(100));
            int count;
            if(mintAmount.compareTo(new BigDecimal("10000"))>=0){
                count = 2;
            }else{
                count = 1;
            }
            for (int i = 0; i < count; i++) {
                AppIssueCardInfo appMallCardInfo = new AppIssueCardInfo();
                appMallCardInfo.setUserId(userId);
                appMallCardInfo.setState(1);
                appMallCardInfo.setDeadline(adminCardConfig.getShelfLife());
                appMallCardInfo.setCreateTime(LocalDateTime.now());
                appMallCardInfo.setAcceleration(acceleration);
                appMallCardInfo.setExpiredTime(appMallCardInfo.getCreateTime().plusDays(adminCardConfig.getShelfLife()));
                appMallCardInfo.setType(2);
               int sss=  appIssueCardInfoMapper.insert(appMallCardInfo);
            }*/
        }else{
            rewardCount = BigDecimalUtil.multiply(mintAmount, new BigDecimal(mintConfig.getRewardRate())).divide(new BigDecimal(100));
        }

        //根据用户id和代币类型获取用户的资产
        AppUserWallet wallet = walletManager.queryWalletByToken(userId, LetokenTokenTypeEnum.LET.getId());
        // 发行数量不能大于自己的有效金额
        if (mintAmount.compareTo(wallet.getAvailableBalance()) > 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_001);
        }
        // 铸币发行记录表
        LocalDateTime now = LocalDateTime.now();
        String uuid = UUIDUtil.getUUID(16);
        AppUserIssueRecord issueRecord = new AppUserIssueRecord();
        issueRecord.setUserId(userId);
        issueRecord.setSn(uuid);
        issueRecord.setIssueAmount(mintAmount);
        issueRecord.setWaitCirculation(rewardCount);
        issueRecord.setCirculation(BigDecimal.ZERO);
        issueRecord.setTotalCirculation(rewardCount);
        issueRecord.setStatus(0);
        issueRecord.setCirculateRound(0);
        issueRecord.setCreateTime(now);
        issueRecord.setTotalCirculation(rewardCount);
        issueRecord.setUpdateTime(now);
        boolean insert = issueRecord.insert();
        if (!insert) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }

        //铸币信息
        AppUserIssue appUserIssue = appUserIssueMapper.selectById(userId);
        if (ObjectUtil.isNull(appUserIssue)) {
            appUserIssue = new AppUserIssue();
            appUserIssue.setUserId(userId);
            appUserIssue.setIssueAmount(BigDecimal.ZERO);
            appUserIssue.setCirculationAmount(BigDecimal.ZERO);
            appUserIssue.setCirculationRemain(BigDecimal.ZERO);
            appUserIssue.setRewardTime(now);
            appUserIssue.setUpdateTime(now);
            appUserIssue.setCountDown(mintConfig.getCirculateDuration()*24*60);
            boolean appUserIssueInsert = appUserIssue.insert();
            if (!appUserIssueInsert) {
                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
            }
        }
        //app_user_issue_history
        AppUserIssueHistory appUserIssueHistory = new AppUserIssueHistory();
        appUserIssueHistory.setUserId(userId);
        appUserIssueHistory.setType(TokenTransactionTypeEnum.ISSUE.getValue());
      //  appUserIssueHistory.setAmount(mintAmount);
        appUserIssueHistory.setAmount(rewardCount);
        appUserIssueHistory.setCreateTime(now);
        boolean issueHistoryInsert = appUserIssueHistory.insert();
        if (!issueHistoryInsert) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }


        // 修改资产表 可用金额=可用金额-铸币发行金额  冻结金额不变   等待释放金额=等待释放金额+铸币奖励
        int flag = wallService.updateUserAmountByUserIDandCoin(mintAmount.negate(),
                BigDecimal.ZERO, rewardCount, userId, LetokenTokenTypeEnum.LET.getId());
        if (flag <= 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }
        int i;
        if(appUserIssue.getCirculationRemain().compareTo(BigDecimal.ZERO) <= 0){
            i = appUserIssueService.updateUserIssueByUseIid(mintAmount, BigDecimal.ZERO, rewardCount, userId, mintConfig.getCirculateDuration()* 24 * 60, 1);
        }else{
            i = appUserIssueService.updateUserIssueByUseIid(mintAmount, BigDecimal.ZERO, rewardCount, userId, null, null);
        }
        if (i <= 0) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_MINT_005);
        }


        AppUserAssetsHistory appUserAssetsHistory = new AppUserAssetsHistory();
        appUserAssetsHistory.setUserId(userId);
        appUserAssetsHistory.setType(TokenTransactionTypeEnum.ISSUE.getValue());
        appUserAssetsHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
        appUserAssetsHistory.setTokenId(LetokenTokenTypeEnum.LET.getId());
        appUserAssetsHistory.setTokenCurrency(LetokenTokenTypeEnum.LET.getName());
        appUserAssetsHistory.setAmount(mintAmount.negate());
       // appUserAssetsHistory.setAmount(rewardCount);
        appUserAssetsHistory.setSn(uuid);
        appUserAssetsHistory.setFromUserName(user.getUserName());
        appUserAssetsHistory.setFromAddress(user.getWalletAddress());
        appUserAssetsHistory.setToAddress("");
        appUserAssetsHistory.setCreateTime(now);
        appUserAssetsHistory.setUpdateTime(now);
        try {
            appUserAssetsHistory.setBalance(walletMapper.getAvailableBalance(appUserAssetsHistory.getTokenId(), appUserAssetsHistory.getUserId()));
        }catch (Exception e){
            log.error("查询可用余额失败 tokenId{} userId{} eMsg{}",appUserAssetsHistory.getTokenId(), appUserAssetsHistory.getUserId(), e.getMessage());
        }
        appUserAssetsHistory.insert();
        if (!user.getInviterId().equals(0)){
            appUserIssueService.upgradeUPdate(user.getId(), mintAmount,3,mintConfig);
        }
        AppUserTeam appUserTeam = appuserTeamMapper.selectById(userId);
        appUserTeam.setAmount(mintAmount);
        appUserTeam.setUserValue(appUserTeam.getUserValue().add(BigDecimalUtil.multiply(mintAmount, new BigDecimal(0.005))));
        appUserTeam.setUserAchievement(appUserTeam.getUserAchievement()+mintAmount.intValue());
        appUserTeam.setRate(new BigDecimal(mintConfig.getCirculateRate()).divide(new BigDecimal(100)));
        appUserTeam.updateById();
        //推荐人获取奖励
        if (!user.getInviterId().equals(0)){
            //生态建设值
            appUserIssueService.addTeamValue(userId, mintAmount,2);
         // appUserIssueService.upgrade(user.getId(), mintAmount, user.getInviterId(),2);
            appUserIssueService.mintRewardsChangeV2(appUserTeam,uuid,mintConfig);
            //动态奖励
            appUserIssueService.ecologicalRewardsV2(appUserTeam,uuid,mintConfig);
            appUserIssueService.peerLevelReward(user.getId(),mintAmount,uuid);
        }
        teamPerformanceService.add(TeamPerformanceTypeEnum.Minting, userId, mintAmount);

    }


    /**
     * 根据顺序返回币种闪兑比例
     *
     * @param
     * @return
     */
    @Override
    public String doSwapProportion(Integer fromType,Integer toType) {
        if (!fromType.equals(LetokenTokenTypeEnum.LET.getId()) && !fromType.equals(LetokenTokenTypeEnum.USDT.getId())){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_016);
        }
        if (!toType.equals(LetokenTokenTypeEnum.LET.getId()) && !toType.equals(LetokenTokenTypeEnum.USDT.getId())){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_EXCHANGE_016);
        }
        AdminSwapConfig swapConfig = adminSwapConfigManager.querySwapPrice(LetokenTokenTypeEnum.LET.getId());
        if (fromType.equals(LetokenTokenTypeEnum.LET.getId())){
            return "1:"+swapConfig.getPrice().stripTrailingZeros();
        }else {
            return swapConfig.getPrice().stripTrailingZeros() + ":1";
        }
    }

}
